package com.server;

import java.util.ArrayList;
import java.util.Enumeration;
import java.util.EventObject;
import java.util.List;
import java.util.Vector;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import cn.com.broad.Board_seat;
import cn.com.cal.PokeCal;
import cn.com.cal.PokeCalVo;
import cn.com.cal.PrudentialCal;
import cn.com.cal.PrudentialVo;
import cn.com.common.Poke;
import cn.com.glopool.GloPool;
import cn.com.listenerInterface.StateListener;
import cn.com.listenerInterface.StateListerImp;
import cn.com.messageManager.MessageManager;
import cn.com.messageprotocal.StateInterface;
import cn.com.user.Poke_User;
import cn.com.zhang.Call;
import cn.com.zhang.SellectCard;
import cn.com.zhang.WinObject;
import cn.com.zhang.Zhang;

import com.server.thread.ConnectionThread;


public class Board_Table extends EventObject 
{
	private static Logger logger = LoggerFactory.getLogger(Board_Table.class);
	public static MessageManager mg = new MessageManager();          //信息管理
	public StateListener listener = new StateListerImp();            //监听
	private int lookcount = 0;                                       //旁观人数	
	private Vector repository = new Vector();                        //
	
	private List<GloPool> glopool = new ArrayList<GloPool>();        // 桌子的彩池列表
	private int nowseconds = 0;                                      //记录计时器当前的秒数
	private int board_state = 1;                                   // 100表示不在游戏中，如果大于等于0，那么表示就在游戏中
	private int id = 0;                                              //桌子的id
	
	private int buymax;                                              //房间的最大买入数
	private int buymin;                                              //房间的最少买入数
	
	private int maxconnection;                                       //最大连接数
	private String table_type;                                       //房间类型
	
	private  int consume_money;                                       //玩一局所要消耗的游戏币
	private  int big_nate;                                            //大注
	private  int little_nate;                                         //小注
	private  List poke_array=new ArrayList();                                    //每一个牌桌要有一副扑克牌,也就是一个有52个牌对象的数组
	private  List<Board_seat> poke_seat = new ArrayList<Board_seat>();           //每个牌桌有7个座位
	private  List<Board_seat> active_list = new ArrayList<Board_seat>();         //座位上有坐位的数组
	private  List<PokeCalVo> completeNu=new ArrayList<PokeCalVo>();              //已结算牛的坐位
	private  List<Poke_User>  looklist=new ArrayList<Poke_User>();               //旁观列表
	private  List<ConnectionThread>   offLineList=new ArrayList<ConnectionThread>();            //掉线玩家表
	

	private boolean if_first = true;                                 		     //标志是不是超时
	

	private boolean if_nu_up=false;                                              //是否出牛了
	private Vector<ConnectionThread> threadpool = new Vector<ConnectionThread>();//保存桌子上的所有连接
	private MessageManager messageManager = new MessageManager();                //信息管理	
	private String password = "";                                                // VIP房设置的密码
	private byte isClock = 0;                                                    //  是否已经加密，0为没有，1为已经加密
	private boolean isplaying = false;
	private byte rob_zhang_time=15;                                               //抢庄倒计时
	private byte rob_now_time=0;
	private List<Zhang> zhang_reponse=new ArrayList<Zhang>();                    //抢庄等待队列
	private List<Call>   call_reponse=new ArrayList<Call>();                     //下注等待队列
	private List<SellectCard> sele_reponse=new ArrayList<SellectCard>();                   //选牌等待队列
	private byte call_time=15;                                                    //下注时间
	private byte call_now_time=0;                                                //下注现在已用时间
	private byte slect_card_time=15;                                             //选牌时间
	private byte slect_now_time=0;                                               //选牌已用时间
	private byte paly_num=0;                                                     //在玩人数
	private byte end_time=20;                                                    //结算等待时间
	private List<Byte> end_time_storage=new ArrayList<Byte>();                   //存储器
	
	

	

	//构造方法
	public Board_Table (Object source) 
	{	
		
		super(source);
		initPoke();
		//初始化座位
		for(int i = 1;i <= 7; i++)
		{
			poke_seat.add( new Board_seat( i, id ) );
		}
		this.addDemoListener(this.listener);
	}

	//初始化扑克牌
	private void initPoke()
	{	
		for( int i = 0;i < 52;i++ )
		{
			switch(i/13)
			{
				case 0:
					int count = 0x0101;
					poke_array.add( new Poke( count + (i%13) ) )	;
					break;
				case 1:
					int count1 = 0x0201;
					poke_array.add( new Poke( count1 + (i%13) ) )	;
					break;
				case 2:
					int count2 = 0x0301;
					poke_array.add( new Poke( count2 + (i%13) ) )	;
					break;
				case 3:
					int count3 = 0x0401;
					poke_array.add( new Poke( count3 + (i%13) ) )	;
					break;
		   }
	  }	
	}
	
	/**
	 * 游戏重新开始，初始化桌子
	 */
	public synchronized int tableInit()
	{
//		if(isplaying)
//		{
//			return 0;
//		}
		isplaying = true;
		this.board_state = 1;
		this.nowseconds = 0;
		this.glopool.clear();		
		this.sele_reponse.clear();
		this.call_reponse.clear();
		this.zhang_reponse.clear();
		this.end_time_storage.clear();
		this.call_now_time=0;
		this.slect_now_time=0;
		this.rob_now_time=0;
		
//		this.poke_array.clear();
		try 
		{
			Thread.sleep(2000);
		} catch (InterruptedException e) 
		{
			logger.error("tableInit 出错：{}", e.getMessage());
		}
		for(int i = 0;i<7;i++)
		{
			if(((Board_seat)(this.getPoke_seat().get(i))).isSeating())
			{
				((Board_seat)(this.getPoke_seat().get(i))).setSeat_state(StateInterface.INIT_STATE);
			}
			((Board_seat)(this.getPoke_seat().get(i))).getPokelist().clear();
			((Board_seat)(this.getPoke_seat().get(i))).setGol_pool(0);
			((Board_seat)(this.getPoke_seat().get(i))).setArray(null);
			((Board_seat)(this.getPoke_seat().get(i))).setNu(null);
		}
		return 1;
	}
	
	

	public synchronized void addDemoListener(StateListener dl)
	{
		repository.addElement(dl); // 这步要注意同步问题
	}
		
	
	
	/*
	 * 判断活动数组里面是否已经存在了这个id的座位,有返回false，没有返回true
	 */
	public boolean check_seat(Board_seat seat)
	{
		
		for(int i = 0;i < active_list.size() ; i++)
		{
			if(seat.getId() == ((Board_seat)(active_list.get(i))).getId())
			{
				return false;
			}
		}
		return true;
	}
	
	//检验最少的钱,具体逻辑事后加
	private boolean checkMoney(int money)
	{
		if(money>0)
		return true;
		return false;
	}
	
	/**
	 * 统计在坐用户拥有的钱数，初始化activelist，不过最小注的1/2，不给加入活动数组
	 */
	public boolean checkUserMoney()
	{
		try{
				this.active_list.clear();  // 清空活动数组
				for(int i =0;i<this.poke_seat.size();i++)
				{
					Board_seat seat = this.poke_seat.get(i);
					
					if(seat.getUserthread() == null && seat.isIs_palying())
					{
						seat.resetSeat();
						this.messageManager.cast_userout(seat.getUserthread().getUser().getUser_id(), this);
						continue;
					}else if(seat.getUserthread() == null)
					{
						continue;
					}
					
					
					if(seat.getUserthread().getUser() == null||!PokeServer.usermap.containsValue(seat.getUserthread().getUser()))
					{
						seat.getUserthread().dispose();//  这里让他消失
						continue;
					}
					
					//验证是否有钱，钱不够弹起(seat.getUserthread().getUser().getIn_money() >= ((Math.ceil(this.getBuymin()*0.025)<3?2:Math.ceil(buymin*0.025))+this.consume_money))
					logger.info(seat.getUserthread().getUser().getUser_name()+"还剩的钱"+seat.getUserthread().getUser().getIn_money());
					if(seat.isSeating() && checkMoney(seat.getUserthread().getUser().getIn_money()))
					{
						this.active_list.add( seat );
						seat.setIs_palying(true);
//						for( int i = 0; i < active_list.size(); i++ )
//						{
//							active_list.get(i).setIs_palying( true ) ;
//							active_list.get(i).setSeat_state(StateInterface.OUT_INIT_STATE);//没有初始化状态
//						}	
					}else if(seat.isSeating()&&seat.getUserthread()!=null)
					{
						logger.info(seat.getUserthread().getUser().getUser_name()+"没钱了，站起来");
						byte[] array = new byte[]{(byte) seat.getId()};
						if(seat.isIf_zhan())
						{
							if_nu_up=true;  //设置重新抢庄
						}
						messageManager.dealStand(array, seat.getUserthread());
					}
					
				}
				paly_num=(byte)this.active_list.size();
				if(this.active_list.size() >= 2)
				{
					this.board_state = 2;//this.board_state = 50;抢庄
					return true;
				}
				else
				{
					this.board_state = 1;//人少，等待时期
					if_first=true;
					return false;
				}
		}catch (Exception e)
		{
			logger.error("method: checkUserMoney() throws error:{}",e.getMessage());
			return false;
		}
	}
	
	/*
	 * 启动总体程序，每次有新的坐下请求我就判断游戏是否正在进行，如果游戏没有开始，而且在坐的用户也达到了
	 * 下线，那么我就调用这个方法来启动洗牌，发牌的程序
	 */
	public synchronized int startup()
	{
		//确保游戏人数能为2才开始
		try
		{
			this.board_state = 1;
			
			//检测是否有断线
			int len=this.offLineList.size();
			if(len>0)
			{
				logger.info("掉线人数:"+len);
				for(int i=0;i<len;i++)
				{
					ConnectionThread threadtemp=offLineList.get(i);
					Poke_User tempUser=threadtemp.getUser();
					messageManager.cast_userout(tempUser.getUser_id(),this);
					logger.info("广播玩家："+tempUser.getUser_id()+"因掉线退出");
					
					//清除相关信息
					Board_seat seat = null;
					if(( seat = threadtemp.getSeat()) != null )
					{
						
						seat.resetSeat();//重置座位
						if(seat.isIf_zhan())
							if_first=true;
						if(threadtemp.getTable().getActive_list().contains(seat))
						{
							threadtemp.getTable().getActive_list().remove(seat);
						}
					}
					
					if( threadtemp.getTable() != null )
					{
						try
						{
							threadtemp.getTable().getThreadpool().remove(this);					
						}catch(Exception e)
						{
							e.printStackTrace();
							logger.error("ConnectionThread 中移除桌子链接线程有错：{}"+e.getMessage());
						}
					}
					
					threadtemp.reset();
				}
			}
			
			offLineList.clear();
			if(checkUserMoney())
			{
				logger.info("是否重新抢庄1"+if_nu_up);
				logger.info("是否重新抢庄2"+if_first);
				if(if_first||if_nu_up)
				{
					if_first=false;
					robZhuang();            //通知抢庄
				}
				else
				{
					this.casecall();
				}
				//this.sender();          //询问选牌
				return 0;
			}
			else
			{
				isplaying =false;
				this.setBoard_state(1);
				return 0;
			}
			
		}catch(Exception e)
		{
			logger.info("startup 方法出错：{}"+e.getMessage());
			this.board_state = 1;
			isplaying =false;
			this.setBoard_state(98);
			return 0;
		}
	}

	/**
	 * 通知抢庄
	 */
	public void robZhuang()
	{
		this.if_nu_up=false;
		zhang_reponse.clear();
		messageManager.cast_zhuang(this,rob_zhang_time);
		this.setBoard_state(2);            //设置抢庄状态
		logger.info("开始抢庄时间");
		for(int i=0;i<rob_zhang_time;i++)  //  定时启动
		{
			rob_now_time=(byte)i;
//			logger.info("开始抢庄时间:"+i);
			try 
			{
				Thread.currentThread().sleep(1000);
			}
			catch (InterruptedException e) 
			{
				e.printStackTrace();
			}
			if(zhang_reponse.size()>=paly_num)
			{
				break;
			}
		}
		endZhange();
	}
	
	/**
	 * 收到通知抢庄
	 */
	public void setRobZhang(byte seatid ,byte ifrobzhang )
	{
		
		if(this.getActive_list().size()<2)
		{
			if_first=true;
			return;
		}
		
		Zhang temp=new Zhang();
		temp.setSeatid(seatid);
		temp.setIfzhang(ifrobzhang);
		zhang_reponse.add(temp);
	}
	
	
	private void reZhang()
	{
		for(int i =0;i<this.poke_seat.size();i++)
		{
			Board_seat seat = this.poke_seat.get(i);
			seat.setIf_zhan(false);
		}
	}
	
	//最终定庄
	private void endZhange()
	{
		if(this.getActive_list().size()<2)
		{
			if_first=true;
			return;
		}
		
		List<Zhang> ss=new ArrayList<Zhang>();
		
		
		reZhang();
		
		for(byte i=0;i<zhang_reponse.size();i++)
		{
			Zhang temp=zhang_reponse.get(i);
			if(temp.getIfzhang()==1)
			{
				ss.add(temp);
			}
		}
		
		zhang_reponse.clear();
		
		if(ss.size()>0)
		{
			Zhang temp3;
			int icount=0;
			boolean b=false;
			for(int j=0;j<ss.size()-1;j++)
			{
				b=false;
				for(int k=0;k<ss.size()-1;k++)
				{
					Zhang temp1=ss.get(k);
					Zhang temp2=ss.get(k+1);
					Board_seat seat = this.poke_seat.get(temp1.getSeatid()-1);
					Board_seat seat1 = this.poke_seat.get(temp2.getSeatid()-1);
					if(seat.getUserthread().getUser().getIn_money()>seat1.getUserthread().getUser().getIn_money());
					{
						ss.set(k,temp2);
						ss.set(k+1,temp1);
						b=true;
					}
					icount++;
				}
				if(!b) 
				break;
			}
			temp3=ss.get(ss.size()-1);
			
			Board_seat seat=this.poke_seat.get(temp3.getSeatid()-1);
			seat.setIf_zhan(true);
			logger.info("庄是："+seat.getUser_id());
			messageManager.cast_zhang_result(this,temp3.getSeatid());
			
			//通知下注
			casecall();
		}
		else
		{
//			messageManager.cast_zhang_result(this,(byte)0);
			//用户站起没做
			for(byte i=0;i<this.active_list.size();i++)
			{
				byte[] array = new byte[]{(byte) this.active_list.get(i).getId()};
				messageManager.dealStand(array, this.active_list.get(i).getUserthread());
			}
		}
	}
	
	private void casecall()
	{
		
		logger.info("开始下注");
		logger.info("活动人数"+paly_num);
		call_reponse.clear();
		messageManager.cast_call(this);
		this.setBoard_state(3); 
		for(int i=0;i<call_time;i++)  //  定时启动
		{
			call_now_time=(byte)i;
//			logger.info("下注倒计时:"+call_now_time);
			try 
			{
				Thread.currentThread().sleep(1000);
			}
			catch (InterruptedException e) 
			{
				e.printStackTrace();
			}
			
			if(call_reponse.size()>=paly_num-1)
			{
				break;
			}
		}
		endCall();
		
	}
	
	private void endCall()
	{
		logger.info("下注结束");
		
		if(call_reponse.size()<=paly_num-1)
		{
			for(byte j=0;j<this.active_list.size();j++)
			{
				Board_seat seat=this.active_list.get(j);
				
				if(seat.isIf_zhan())
				{
					continue;
				}
				
				int user_id=seat.getUser_id();
				byte tempSeat=(byte)seat.getId();
				byte flag=0;
				for(byte i=0;i<call_reponse.size();i++)
				{
					flag=i;
					if(tempSeat==call_reponse.get(i).getSeatid())
					{
						break;
					}
					else
					{
						continue;
					}
				}
				
				if(flag==(call_reponse.size()))
				{
					seat.setGol_pool(little_nate);
					messageManager.cast_call_do(this, tempSeat, little_nate,user_id);
				}
			}
		}
		ruffle() ;  //洗牌
		
		this.deal();            //发牌
		this.sender();               //选牌				
	}
	
	/**
	 * 下注返回
	 * @param seatId
	 * @param money
	 */
	public void callResponse(byte seatId,int money)
	{
		Call temp=new Call();
		temp.setSeatid(seatId);
		temp.setCall(money);
		Board_seat seat=this.poke_seat.get(seatId-1);
		seat.setGol_pool(money);
		call_reponse.add(temp);			
	}
	
	/**
	 * 开局初始操作
	 * 洗牌
	 * @param list
	 * @return
	 */
	public void ruffle()
	{
		logger.info("洗牌程序");
			
			try 
			{
				Thread.currentThread().sleep(2000);
			} catch (InterruptedException e) 
			{
				logger.error("method: ruffle() line 219 throws error: {}",e.getMessage());				
			}
			
		try
		{
			int size=this.poke_array.size();
			Object temp_obj=null;
			//洗牌
			for(int i=0;i<size;i++)
			{
			  int m=(int) (Math.random()*size);
			  temp_obj=poke_array.get(m);
			  poke_array.set(m, poke_array.get(i));
			  poke_array.set(i, temp_obj);
			}
			
		   //扣除底钱
//			if(deduct_fundus() == 100)
//			{
//				return 100;
//			}else
//			{
//				return 98;
//			}
		}catch (Exception e)
		{
			logger.info("ruffle 出错：{}  ", e.getMessage());
		}
	}
	
	/**
	 * 发牌
	 */
	public synchronized void deal()  //  如果返回一个 0 ，那么就不再发牌，计算是否有边池的存在，根据 activelist 进行彩池的分配
	{
		try
		{
			int flag_count = 0;
			List<Board_seat> seatlist = new ArrayList<Board_seat>();
			board_state=3;   //  改变桌子的状态,改为选牌状态
			for(int i=0;i<7;i++)
			{
				Board_seat seat = this.poke_seat.get(i);
				seat.getPokelist().clear();
				if(seat.isIs_palying() && seat.isSeating()  )
				{					
					seat.getPokelist().add(((Poke)poke_array.get(flag_count++)));
					seat.getPokelist().add(((Poke)poke_array.get(flag_count++)));
					seat.getPokelist().add(((Poke)poke_array.get(flag_count++)));
					seat.getPokelist().add(((Poke)poke_array.get(flag_count++)));
					seat.getPokelist().add(((Poke)poke_array.get(flag_count++)));
					messageManager.deal_three(seat, this);   //   发牌发给客户
					seatlist.add(seat);
				}
			}
			messageManager.cast_three(this);
			
		}catch(Exception e)
		{
			e.printStackTrace();
			logger.error("deal 方法出错：{}", e.getMessage());
		}
    }
	
	
	
	
/**
 * 询问的一轮调用的方法
 */
private void sender()
{ 
	try
	{
			if( active_list.size() <= 1 )
			{
				return ;
			}
			
			messageManager.cast_selet(this, slect_card_time);  //广播询问信息
			this.setBoard_state(4); 
			logger.info("开始选牌");
			logger.info("活动人数"+paly_num);
			for(int i=0;i<slect_card_time;i++)  //  定时启动
			{
				slect_now_time=(byte)i;
			//	logger.info("选牌倒计时:"+slect_now_time);
				try 
				{
					Thread.currentThread().sleep(1000);
				}
				catch (InterruptedException e) 
				{
					e.printStackTrace();
				}
				
				if( active_list.size() <= 1 )
				{
					return;
				}
				logger.info("已选牌响应"+sele_reponse.size());
				if(sele_reponse.size()>=paly_num)
				{
					break;
				}				
			}
			
			selectEnd();
			
	}catch(Exception e)
	{
		e.printStackTrace();
		logger.error("sender 出错：{}", e.getMessage());
	}
}

private void selectEnd()
{
	logger.info("选牌结束");
	if(sele_reponse.size()<active_list.size())
	{
		for(int i=0;i<active_list.size();i++)
		{
			Board_seat seat=active_list.get(i);
			if(seat.getNu()==null)
			{
			
				List<Poke> pokeList=seat.getPokelist();
				PokeCal temp=new PokeCal(pokeList);
				temp.setNuType(10);
				
				int[] cardArray=new int[5];
				for(int j=0;j<pokeList.size();j++)
				{
					cardArray[j]=pokeList.get(j).getFlag();
				}
				byte seat_id=(byte)seat.getId();
				int user_id=seat.getUser_id();
				seat.setNu(temp);
				messageManager.cast_sele_do(this,cardArray,10,seat_id,user_id);
			}
		}
	}	
//	sele_reponse.clear();
	this.calEnd();
}

/**
 * 收到选牌操作
 * @param seatid
 * @param cardArray
 * @param nutype
 */
public void checkSelectCard(byte seatid,int[] cardArray,byte nutype)
{
	SellectCard temp1=new SellectCard();
	temp1.setCardArray(cardArray);
	temp1.setSeatid(seatid);
	temp1.setNuType(nutype);
	
	sele_reponse.add(temp1);
	
	Board_seat seat = this.poke_seat.get(seatid-1);
	List<Poke> pokelist=seat.getPokelist();
	PokeCal nuCheck=new PokeCal(pokelist);
	boolean check=nuCheck.checkNu(cardArray, nutype);
	seat.setNu(nuCheck);
	int user_id=seat.getUser_id();
	if(check)
	{
		logger.info("牛值验证成功");
		messageManager.cast_sele_do(this,cardArray,nutype,seatid,user_id);
		if(nutype>29)
		{
			logger.info("有牛，记录抢庄");
			if_nu_up=true;
		}
	}
	else
	{
		logger.info("牛值验证失败");
		messageManager.cast_sele_do(this,cardArray,10,seatid,user_id);
	}
}
	
/**
 * 最后的计算，
 * 比较牌面的大小，
 * 彩池的分配，
 * 然后通知重启游戏
 *根据彩池进行取值进行比较
 */
public void calEnd() 
{
	sele_reponse.clear();
	try
	{
		logger.info("calend1");
		this.setBoard_state(5); 
		Board_seat seat= null;
		List<WinObject> winlist=new ArrayList<WinObject>();
		Board_seat zhanSeat=null;
		logger.info("calend2");
		for(byte i=0;i<this.active_list.size();i++)
		{
			logger.info("calend3");
			Board_seat tempSeat=this.active_list.get(i);
			if(tempSeat.isIf_zhan())
			{
				logger.info("calend4");
				zhanSeat=tempSeat;
				break;
			}
		}
		logger.info("calend5");
		int zhanType=0;
		if(zhanSeat!=null)
		{
			zhanType=zhanSeat.getNu().getNuType();
		}
		else
		{
			logger.info("没有找到庄");
			logger.info("calend6");
		}
		
		WinObject zhangWin=new WinObject();
		zhangWin.setIf_zhang(true);
		zhangWin.setSeat_id((byte)zhanSeat.getId());
		zhangWin.setUser_id(zhanSeat.getUserthread().getUser().getUser_id());
		Poke_User tempuser=null;
		double zhanEnd=0;
		logger.info("calend7");
		for(byte j=0;j<this.active_list.size();j++)
		{
			logger.info("calend8");
			Board_seat tempSeat=this.active_list.get(j);
			tempuser=tempSeat.getUserthread().getUser();
			if(zhanSeat==tempSeat)
			{
				continue;
			}
			logger.info("calend9");
			int tempType=tempSeat.getNu().getNuType();
			
			WinObject tempWin=new WinObject();
			tempWin.setIf_zhang(false);
			tempWin.setSeat_id((byte)tempSeat.getId());
			tempWin.setUser_id(tempSeat.getUserthread().getUser().getUser_id());
			int money;
			if(zhanType>tempType)
			{
				
				money=zhanSeat.getNu().getFanBai()*tempSeat.getGol_pool();
				logger.info("庄牌型大:"+money);
			}else if (zhanType<tempType)
			{
				logger.info("庄牌型小");
				money=(-1)*tempSeat.getNu().getFanBai()*tempSeat.getGol_pool();
			}
			else
			{
				logger.info("牌型相等");
				Poke poke1=zhanSeat.getNu().getCardNum(0);
				Poke poke2=tempSeat.getNu().getCardNum(0);
				if(poke1.getValue()>poke2.getValue())
				{
					logger.info("庄牌第一张值大");
					money=zhanSeat.getNu().getFanBai()*tempSeat.getGol_pool();
				}
				else if(poke1.getValue()<poke2.getValue())
				{
					logger.info("庄牌第一张值小");
					money=(-1)*tempSeat.getNu().getFanBai()*tempSeat.getGol_pool();
				}
				else
				{
					logger.info("庄牌值相等，比花色");
					if(poke1.getShap()>poke2.getShap())
					{
						money=zhanSeat.getNu().getFanBai()*tempSeat.getGol_pool();
					}
					else
					{
						money=(-1)*tempSeat.getNu().getFanBai()*tempSeat.getGol_pool();
					}
				}
			}
			logger.info("calend10");
			zhanEnd+=money;
			tempuser.setIn_money(tempuser.getIn_money()-money);  //修改钱
			tempWin.setMoney((-1)*money);
			winlist.add(tempWin);
		}
		logger.info("calend11");
		tempuser=zhanSeat.getUserthread().getUser();
		tempuser.setIn_money(tempuser.getIn_money()+(int)zhanEnd);
		zhangWin.setMoney(zhanEnd);
		winlist.add(zhangWin);
		logger.info("通知结算");
		messageManager.cast_end_settlement(this,winlist);
		logger.info("calend12");
		endwait();
	}catch(Exception e)
	{
		logger.info("calEnd 出错："+e.getMessage());
	}
}

private void endwait()
{
	logger.info("开始结算");
	for(int i=0;i<end_time;i++)  //  定时启动
	{
		int slect_now_time=(byte)i;
		//logger.info("结算倒计时:"+slect_now_time);
		try 
		{
			Thread.currentThread().sleep(1000);
		}
		catch (InterruptedException e) 
		{
			e.printStackTrace();
		}
		logger.info("已结算响应"+end_time_storage.size());
		if(end_time_storage.size()>=active_list.size())
		{
			break;
		}
	}
	
	endBoard();
}

private void endBoard()
{
	logger.info("结算完成，重新开盘");
	end_time_storage.clear();
	this.tableInit();
	this.startup();
}

public void setEndWait(byte seatid)
{
	end_time_storage.add((Byte)seatid);
}

	/**
	 * 当活动数组只剩下一个用户的时候，
	 * 把所有的钱都给用户当前的活动数组里面的用户
	 * 首先将所有用户的钱回归彩池，然后重启游戏计数进行游戏
	 */
	public void balckOut()
	{
//		try{
//		//  把所有的钱存到最后一个彩池，然后把所有的彩池都分配给这个活动数组中的用户，然后重启游戏
//		int size = this.getGlopool().size();//得到彩池的数量
//		GloPool gpool = this.getGlopool().get(size - 1);
//		Board_seat seat =null;
//		int countmoney = 0;
//		for(int i = 0;i<7;i++){  // 设置所有的彩池为空，然后加入最后的彩池
//			seat = this.poke_seat.get(i);
////			gpool.setMoney(gpool.getMoney()+)
//			if(seat.getGol_pool() > 0){
//				countmoney += seat.getGol_pool();
//				seat.setGol_pool(0);
//				}
//		}
//		gpool.setMoney( gpool.getMoney() + countmoney );
//		//this.getMessageManager().castGolpool(this); // 发送一条桌子彩池数组
//		//告诉客户端这个用户赢了，有哪些彩池是他的，分配才是，改变游戏状态，重新开始
//		//一个用户的状态， 所有的彩池都是他的   
//		List<Integer> array = new ArrayList<Integer>();
//		int winmoney = 0;
//		for(int n = 0; n < this.getGlopool().size() ; n++){
////			array.add(n);
//			winmoney += this.getGlopool().get(n).getMoney();
//			array.add( this.getGlopool().get(n).getMoney() );
//		}
//		try{
//		seat = this.active_list.get(0);
//		}catch(Exception e)
//		{
//			//e.printStackTrace();
//			this.glopool.clear();
//			this.messageManager.castGameOver( this );
//			this.tableInit();
//			logger.error("java.lang.IndexOutOfBoundsException: Index: 0, Size: 0");
//			return;
//		}
//		
//		if( winmoney > 0 )
//		{
//		seat.getUserthread().getUser().setIn_money( seat.getUserthread().getUser().getIn_money() + winmoney );
//		}
//		else
//		{
//			this.glopool.clear();
//			return;
//		}
//		Object[] obarray = new Object[]{seat.getUserthread().getUser().getUser_id()+"/"+seat.getUserthread().getUser().getUser_name()+"/"+seat.getId(),this.getId(),winmoney};
//		logger.info("赢钱：user/username/seatid {} at  the id of this table is {} wined {}",obarray);
//		//this.messageManager.castWinner( seat.getId(), array, this );  //  广播赢的用户
//		this.board_state = 88;
//		try {
//			Thread.currentThread().sleep(1000);
//		} catch (InterruptedException e) {
//			e.printStackTrace();
//			logger.error("balckOut 出错：{}", e.getMessage());
//		}
//		this.messageManager.castGameOver( this );
//		this.isplaying = false;
//		}catch(Exception e){
//			e.printStackTrace();
//			logger.error("balckOut 方法出错：{}", e.getMessage());
//			this.messageManager.castGameOver( this );
//			this.isplaying = false;
//		}
	}
	


	// 如果这里没有使用Vector而是使用ArrayList那么要注意同步问题
	public synchronized void notifyDemoEvent(Board_Table  event)
	{
		try
		{
			Enumeration enuma = repository.elements();// 这步要注意同步问题
			while( enuma.hasMoreElements() )
			{ 
			   listener = (StateListener)enuma.nextElement();
			   listener.demoEvent(event);
			} 
		}catch(Exception e)
		{
			e.printStackTrace();
			logger.error(" event notifyDemoEvent 出错：{}", e.getMessage());
			//this.getMessageManager().castGameOver( this );  //  广播游戏结束
			List<Byte> list = new ArrayList<Byte>();
			for(int i=0;i<this.getPoke_seat().size();i++)
			{
				  if(((Board_seat)(this.getPoke_seat().get(i))).getUserthread() == null||
						  ((Board_seat)(this.getPoke_seat().get(i))).getUserthread().getUser() == null)
				  {
					  list.add((byte) ((Board_seat)(this.getPoke_seat().get(i))).getId());
				  }
			  }
			  this.getMessageManager().clearSeat(this, list);
			  this.setIsplaying(false);
			  if(this.tableInit()>0)
			  {
				  logger.error(" event notifyDemoEvent 出错之后游戏启动,桌子状态:{}", this.getBoard_state());
				  this.startup();
			  }
		}
   }

// 删除监听器，如果这里没有使用Vector而是使用ArrayList那么要注意同步问题
public synchronized void removeDemoListener(StateListener dl) 
{
	repository.remove(dl);// 这步要注意同步问题
	dl=null;
}
		
  public synchronized void setBoard_state(int state)
  { 
	  if(repository.size() == 0)
	  {
		  this.addDemoListener(this.listener);
	  }
	  try
	  {
//		  boolean bool=false; 
//		  
//		  if(state == 1)
//		  {
//			  bool=true; 
//		  }
		  this.board_state = state; //如果改变则执行事件 
//		  if(bool)
//		  {
//	          notifyDemoEvent( this ); 
//	      }
	  }catch(Exception e)
	  {
		  logger.error(" event setBoard_state 出错：{}", e.getMessage());
	  }
  }
	  

	
	public  int getBoard_state() {
		return board_state;
	}
	
	public  int getBuymax() {
		return buymax;
	}
	public  int getBuymin() {
		return buymin;
	}
	
	public  List<Board_seat> getActive_list() {
		return active_list;
	}
	
	public byte getActive_list_size(){
		return (byte) active_list.size();
	}
	
	public  List<Board_seat> getPoke_seat() {
		return poke_seat;
	}

	public int getTableId() {
		return id;
	}
	public void setId(int id) {
		this.id = id;
	}
	
	public MessageManager getMessageManager() {
		return messageManager;
	}
	public void setMessageManager(MessageManager messageManager) {
		this.messageManager = messageManager;
	}
	public List getPoke_array() {
		return poke_array;
	}
	public void setPoke_array(List poke_array) {
		this.poke_array = poke_array;
	}
	public Vector<ConnectionThread> getThreadpool() {
		return threadpool;
	}
	public void setThreadpool(Vector<ConnectionThread> threadpool) {
		this.threadpool = threadpool;
	}
	

	public void setBuymax(int buymax) {
		this.buymax = buymax;
	}
	public void setBuymin(int buymin) {
		this.buymin = buymin;
	}
	


	public int getConsume_money() {
		return consume_money;
	}

	public void setConsume_money(int consume_money) {
		this.consume_money = consume_money;
	}

	public int getMaxconnection() {
		return maxconnection;
	}


	public void setMaxconnection(int maxconnection) {
		this.maxconnection = maxconnection;
	}
	public String getTable_type() {
		return table_type;
	}

	public void setTable_type(String table_type) {
		this.table_type = table_type;
	}

	public int getBig_nate() {
		return big_nate;
	}

	public void setBig_nate(int big_nate) {
		this.big_nate = big_nate;
	}

	public int getLittle_nate() {
		return little_nate;
	}

	public void setLittle_nate(int little_nate) {
		this.little_nate = little_nate;
	}

	

	public List<GloPool> getGlopool() {
		return glopool;
	}

	public void setGlopool(List<GloPool> glopool) {
		this.glopool = glopool;
	}


	public int getId() {
		return id;
	}

	public int getNowseconds() {
		return nowseconds;
	}
	public StateListener getListener() 
	{
		return listener;
	} 
	
	public int getLookcount() 
	{
		return lookcount;
	}

	public void setLookcount(int lookcount) 
	{
		this.lookcount = lookcount;
	}
	public List<Poke_User> getLooklist() {
		return looklist;
	}

	public void setLooklist(List<Poke_User> looklist) {
		this.looklist = looklist;
	}
	
	public List<Call> getCall_reponse() {
		return call_reponse;
	}

	public List<SellectCard> getSele_reponse() {
		return sele_reponse;
	}

	public byte getCall_now_time() {
		return call_now_time;
	}

	public byte getSlect_card_time() {
		return slect_card_time;
	}
	public byte getRob_now_time() {
		return rob_now_time;
	}
	public List<Zhang> getZhang_reponse() {
		return zhang_reponse;
	}
	 public byte getSlect_now_time() {
			return slect_now_time;
		}
	//是否在玩
	public boolean isIsplaying() 
	{
		return isplaying;
	}
	//是否在玩
	public void setIsplaying(boolean isplaying) 
	{
		this.isplaying = isplaying;
	}
    //是否加密
	public byte getIsClock() 
	{
		return isClock;
	}
//	是否加密
	public void setIsClock(byte isClock) 
	{
		this.isClock = isClock;
	}
    //获取密码
	public String getPassword() 
	{
		return password;
	}
//	设置密码
	public void setPassword(String password) 
	{
		this.password = password;
	}
	
	public Board_seat getBoSeat(int id)
	{
		Board_seat seat= null;
		for(int i = 0;i<7;i++)
		{
			if(id == ((Board_seat)(this.getPoke_seat().get(i))).getId())
			{
				seat = ((Board_seat)(this.getPoke_seat().get(i)));
				return seat;
			}
		}
		return seat;
	}
	public byte getPaly_num() {
		return paly_num;
	}

	public void setPaly_num(byte paly_num) {
		this.paly_num = paly_num;
	}
	
	public List<Byte> getEnd_time_storage() {
		return end_time_storage;
	}

	public void setEnd_time_storage(List<Byte> end_time_storage) {
		this.end_time_storage = end_time_storage;
	}
	
	public boolean isIf_first() {
		return if_first;
	}

	public void setIf_first(boolean if_first) {
		this.if_first = if_first;
	}
	public List<ConnectionThread> getOffLineList() {
		return offLineList;
	}

	public void addOffLineList(ConnectionThread  thread1) {
		this.offLineList.add(thread1);
	}
	/*
	 * 扣除底钱 此方法暂不用
	 */
	/*
	public int deduct_fundus() 
	{
		try
		{
			GloPool allpool = new GloPool();
			glopool.add(allpool);
		
		//扣除房间消耗
			byte[] seatid=new byte[active_list.size()];
			for(int i = 0 ; i < active_list.size(); i++)
			{
				Board_seat seat = active_list.get(i);
			
				seat.getUserthread().getUser().setIn_money( seat.getUserthread().getUser().getIn_money() - call_money - this.consume_money );
				seat.getUserthread().getUser().setM_count(seat.getUserthread().getUser().getM_count()+1);  //  场次加1
				allpool.setMoney( allpool.getMoney()+call_money );//  将扣除的底钱加到一号彩池
				allpool.getList().add(seat);   //   加入相关列表
				this.allmoney += call_money;
			
				if(call_money == this.getLittle_nate())
				{
					least_call_money = call_money;
					this.most_call_money =this.little_nate;  
				}
				else
				{
					least_call_money =(int) Math.ceil(((this.getLittle_nate())*0.5) - call_money);
					this.most_call_money = this.little_nate - least_call_money;   // 设置起始的最大限额
				}
				seatid[i]=(byte) seat.getId();
				}
		
			//广播扣除底钱的信息
			messageManager.cast_deduct( seatid , this );
			return 100;
		}catch(Exception e)
		{
			logger.error("deduct_fundus  has ERROR:{}", e.getMessage());
			return 98;
		}
		
	}
	*/	
}
